<template>
	<el-dialog :close-on-click-modal="false" :destroy-on-close="true" title="查看" draggable v-model="visible" width="65%" @close="onCancel">
		<el-form :model="form" :rules="dataRules" formDialogRef label-width="120px" ref="dataFormRef" v-loading="loading">
			<el-row :gutter="20" style="margin-left: -55px !important; margin-right: 140px !important">
				<el-col :span="8" class="mb20">
					<el-form-item label="场景名称" prop="sceneName">
						<el-input placeholder="请输入场景名称" disabled v-model="form.sceneName" />
					</el-form-item>
				</el-col>
				<el-col :span="8" class="mb20">
					<el-form-item label="触发方式" prop="type">
						<el-select disabled v-model="form.type" placeholder="请选择触发方式">
							<el-option :key="index" :label="item.label" :value="item.value" v-for="(item, index) in timingOptions"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="8" class="mb20">
					<el-form-item label="业务类型" prop="actionType">
						<el-select disabled v-model="form.actionType" placeholder="请选择业务类型">
							<el-option label="联动" value="0"></el-option>
							<el-option label="告警" value="1"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="8" class="mb20">
					<el-form-item label="场景描述" prop="description">
						<el-input disabled placeholder="请输入场景描述" v-model="form.description" />
					</el-form-item>
				</el-col>
			</el-row>
			<!-- 触发器 -->
			<div>
				<div class="title_name">
					<div>触发器</div>
				</div>
				<div class="box" v-for="(item, indexOne) in form.sceneTriggerList" :key="item.key">
					<el-form :model="item" label-width="120px" :rules="chufaqiRules" ref="formItem">
						<div class="chufaqi">
							<div class="trigger_title">触发器{{ indexOne + 1 }}</div>
							<el-row :gutter="20">
								<el-col :span="5" class="mb20">
									<el-form-item prop="triggerMode">
										<el-select disabled v-model="item.triggerMode" placeholder="请选择设备">
											<el-option :key="index" :label="item.label" :value="item.value" v-for="(item, index) in typeOptions"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 1">
									<el-form-item prop="equipmentName">
										<el-select disabled v-model="item.equipmentName" placeholder="请选择设备类型" @change="handleChangType($event, indexOne)">
											<el-option :key="index" :label="item.name" :value="item.identify" v-for="(item, index) in equipmentOptions"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 1">
									<el-form-item prop="productName">
										<el-select disabled v-model="item.productName" placeholder="请选择设备产品" @change="handleChangProduct($event, indexOne)">
											<el-option
												:key="index1"
												:label="item1.name"
												:value="item1.productKey"
												v-for="(item1, index1) in item.productOptions"
											></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20 select_width" v-if="item.triggerMode == 1">
									<el-form-item prop="unitNo">
										<el-select
											disabled
											collapse-tags
											multiple
											filterable
											placeholder="请选择设备信息"
											v-model="item.unitNo"
											@change="handleChangInformation($event, indexOne)"
										>
											<template #header>
												<el-button text @click="changeUnitNo('trigger', true, indexOne)">全选</el-button>
												<el-button text @click="changeUnitNo('trigger', false, indexOne)">全取消</el-button>
											</template>
											<el-option
												:key="index2"
												:label="item2.deviceName"
												:value="item2.unitNo"
												v-for="(item2, index2) in item.accessDeviceInfoOptions"
												@click.native="getCorpAndDept(item2.productKey, indexOne)"
											></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 1">
									<el-form-item prop="channelNo">
										<el-select disabled v-model="item.channelNo" placeholder="请选择信号类型" @change="handleOnlineOffline" value-key="identifier">
											<el-option
												:key="item3.identifier"
												:label="item3.name"
												:value="form.id == '' ? item3 : item3.identifier"
												v-for="(item3, index3) in item.informationOptions"
											></el-option>
											<el-option :key="-1" label="在线" value="online"></el-option>
											<el-option :key="-2" label="离线" value="offonline"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 1 && onlineOffline != 'online' && onlineOffline != 'offonline'">
									<el-form-item prop="configType">
										<el-select disabled v-model="item.configType" placeholder="请选择触发类型">
											<el-option :key="index" :label="item.label" :value="item.value" v-for="(item, index) in triggerTypeOptions"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col
									:span="5"
									class="mb20"
									v-if="
										(item.triggerMode == 1 && item.configType == 0 && onlineOffline != 'online' && onlineOffline != 'offonline') ||
										item.configType == 1 ||
										item.configType == 2 ||
										item.configType == 4 ||
										item.configType == 5
									"
								>
									<el-form-item prop="fixedValue">
										<el-input disabled placeholder="请输入固定值" v-model="item.fixedValue" />
									</el-form-item>
								</el-col>
								<el-col
									:span="5"
									class="mb20"
									v-if="
										item.triggerMode == 1 &&
										(item.configType == 3 || item.configType == 6) &&
										onlineOffline != 'online' &&
										onlineOffline != 'offonline'
									"
								>
									<el-form-item>
										<div style="display: flex">
											<el-input disabled v-model="item.upperValue" style="width: 110px" placeholder="请输入上限值" clearable />
											<el-input disabled v-model="item.lowerValue" style="width: 110px" placeholder="请输入下限值" clearable />
										</div>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 1 && onlineOffline != 'online' && onlineOffline != 'offonline'">
									<el-form-item prop="triggerConfig">
										<el-select disabled v-model="item.triggerConfig" placeholder="请选择触发机制">
											<el-option :key="index" :label="item.label" :value="item.value" v-for="(item, index) in mechanismOptions"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 1 && item.triggerConfig == 1">
									<el-form-item prop="second">
										<el-input-number disabled placeholder="请输入触发秒数" v-model="item.second" :min="0" :max="86400" />
									</el-form-item>
								</el-col>

								<!-- 定时触发 -->
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 2">
									<el-form-item prop="triggerConfig">
										<el-time-picker
											disabled
											value-format="HH:mm:ss"
											format="HH:mm:ss"
											v-model="item.timingSetTime"
											@change="changeTiming"
											placeholder="请选择开始时间"
										/>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 2">
									<el-form-item prop="week">
										<el-select disabled collapse-tags multiple v-model="item.week" placeholder="请选择周期">
											<template #header>
												<el-button text @click="changeWeek(true, indexOne)">全选</el-button>
												<el-button text @click="changeWeek(false, indexOne)">全取消</el-button>
											</template>
											<el-option :key="index" :label="item.label" :value="item.value" v-for="(item, index) in weekOptions"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 2">
									<el-form-item prop="specialDate">
										<div
											disabled
											style="margin-left: 20px; cursor: pointer; color: #38b0de; font-size: 16px; font-weight: 600"
											@click="handleSpecialDates(item, indexOne)"
										>
											特殊日期
										</div>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 2">
									<!-- <el-button style="margin-left: 170px" @click="changeIptShow(item, indexOne)">高级<br>选项</el-button> -->
									<div disabled style="margin-left: 170px; cursor: pointer" @click="changeIptShow(item, indexOne)">高级<br />选项</div>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 2 && item.iptShow">
									<el-form-item prop="triggerNumber">
										<el-input disabled placeholder="请输入重复触发次数" v-model="item.triggerNumber" />
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 2 && item.iptShow">
									<el-form-item prop="intervalTime">
										<el-input-number
											disabled
											placeholder="请输入间隔时间"
											v-model="item.intervalTime"
											:min="0"
											@change="changeIntervalTimeMax"
											:max="intervalTimeMax"
										>
										</el-input-number>
									</el-form-item>
								</el-col>
							</el-row>
						</div>
					</el-form>
				</div>
			</div>
			<!-- 执行条件 -->
			<div style="margin-top: 12px">
				<div class="title_name">
					<div>
						<div class="shaixuan_select">
							<div>执行条件</div>
							<div class="manzu">需满足一下</div>
							<div>
								<el-select disabled v-model="form.conditions" clearable placeholder="请选择条件" style="width: 125px">
									<el-option v-for="item in conditionOptions" :key="item.value" :label="item.label" :value="item.value" />
								</el-select>
							</div>
							<div class="tiaojian">条件</div>
						</div>
					</div>
				</div>
				<div class="box" v-for="(item, indexOne) in form.sceneExecuteConditionsList" :key="item.key">
					<el-form :model="item" label-width="120px" :rules="chufaqiRules" ref="formItem">
						<div class="chufaqi" style="width: 1123px">
							<div class="trigger_title">执行条件{{ indexOne + 1 }}</div>
							<el-row :gutter="20">
								<el-col :span="5" class="mb20">
									<el-form-item prop="triggerMode">
										<el-select disabled v-model="item.triggerMode" placeholder="请选择设备条件">
											<el-option :key="index" :label="item.label" :value="item.value" v-for="(item, index) in conditionForOptions"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<!-- 设备属性 -->
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 1">
									<el-form-item prop="equipmentName">
										<el-select
											disabled
											v-model="item.equipmentName"
											placeholder="请选择设备类型"
											@change="handleChangconditionType($event, indexOne)"
										>
											<el-option :key="index" :label="item.name" :value="item.identify" v-for="(item, index) in equipmentOptions"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 1">
									<el-form-item prop="productName">
										<el-select
											disabled
											v-model="item.productName"
											placeholder="请选择设备产品"
											@change="handleChangConditionProduct($event, indexOne)"
										>
											<el-option
												:key="index1"
												:label="item1.name"
												:value="item1.productKey"
												v-for="(item1, index1) in item.productConditionOptions"
											></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20 select_width" v-if="item.triggerMode == 1">
									<el-form-item prop="unitNo">
										<el-select
											disabled
											collapse-tags
											multiple
											filterable
											placeholder="请选择设备信息"
											v-model="item.unitNo"
											@change="handleChangConditionInformation($event, indexOne)"
											style="width: 300px"
										>
											<template #header>
												<el-button text @click="changeUnitNo('conditions', true, indexOne)">全选</el-button>
												<el-button text @click="changeUnitNo('conditions', false, indexOne)">全取消</el-button>
											</template>
											<el-option
												:key="index2"
												:label="item2.deviceName"
												:value="item2.unitNo"
												v-for="(item2, index2) in item.accessConditionOptions"
												@click.native="getConditionAndDept(item2.productKey, indexOne)"
											></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 1">
									<!-- <el-form-item prop="channelNo">
									<el-select v-model="item.channelNo" placeholder="请选择信号类型" @change="handleOnlineOfflineOne" value-key="identifier">
										<el-option :key="item.identifier" :label="item.name" :value="item" v-for="(item, index) in informationConditionOptions"></el-option>
										<el-option :key="-1" label="在线" value="online"></el-option>
										<el-option :key="-2" label="离线" value="offonline"></el-option>
									</el-select>

								</el-form-item> -->
									<el-form-item prop="channelNo">
										<el-select disabled v-model="item.channelNo" placeholder="请选择信号类型" @change="handleOnlineOfflineOne" value-key="identifier">
											<el-option
												:key="item.identifier"
												:label="item.name"
												:value="form.id == '' ? item : item.identifier"
												v-for="(item, index) in item.informationConditionOptions"
											></el-option>
											<el-option :key="-1" label="在线" value="online"></el-option>
											<el-option :key="-2" label="离线" value="offonline"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 1 && onlineOfflineOne != 'online' && onlineOfflineOne != 'offonline'">
									<el-form-item prop="configType">
										<el-select disabled v-model="item.configType" placeholder="请选择触发类型">
											<el-option :key="index" :label="item.label" :value="item.value" v-for="(item, index) in triggerTypeOptions"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col
									:span="5"
									class="mb20"
									v-if="
										(item.triggerMode == 1 && item.configType == 0 && onlineOfflineOne != 'online' && onlineOfflineOne != 'offonline') ||
										item.configType == 1 ||
										item.configType == 2 ||
										item.configType == 4 ||
										item.configType == 5
									"
								>
									<el-form-item prop="fixedValue">
										<el-input disabled placeholder="请输入固定值" v-model="item.fixedValue" />
									</el-form-item>
								</el-col>
								<el-col
									:span="5"
									class="mb20"
									v-if="
										item.triggerMode == 1 &&
										(item.configType == 3 || item.configType == 6) &&
										onlineOfflineOne != 'online' &&
										onlineOfflineOne != 'offonline'
									"
								>
									<el-form-item>
										<div style="display: flex">
											<el-input disabled v-model="item.upperValue" style="width: 110px" placeholder="请输入上限值" clearable />
											<el-input disabled v-model="item.lowerValue" style="width: 110px" placeholder="请输入下限值" clearable />
										</div>
									</el-form-item>
								</el-col>

								<!-- 时间范围 -->
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 2">
									<el-form-item prop="timeScope">
										<el-select disabled v-model="item.timeScope" placeholder="请选择时间方式">
											<!-- style="margin-left: 170px; cursor: pointer" -->
											<el-option :key="index" :label="item.label" :value="item.value" v-for="(item, index) in timeModeOptions"></el-option>
										</el-select>
									</el-form-item>
								</el-col>

								<el-col :span="5" class="mb20" v-if="item.triggerMode == 2 && item.timeScope == 1">
									<el-form-item prop="startTime" placeholder="请选择开始时间">
										<el-date-picker disabled v-model="item.startTime" type="datetime" placeholder="请选择开始时间" />
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 2 && item.timeScope == 1">
									<el-form-item prop="endTime" placeholder="请选择结束时间">
										<el-date-picker disabled v-model="item.endTime" type="datetime" placeholder="请选择结束时间" />
									</el-form-item>
								</el-col>
							</el-row>
						</div>
					</el-form>
				</div>
			</div>
			<!-- 执行动作 -->
			<div style="margin-top: 12px">
				<div class="title_name">
					<div style="margin-top: 5px"><span style="color: red; margin-right: 3px">*</span>执行动作</div>
				</div>
				<div class="box" v-for="(item, indexOne) in form.sceneExecuteActionList" :key="item.key">
					<el-form :model="item" label-width="130px" :rules="chufaqiRules" ref="formItem">
						<div class="chufaqi" style="width: 1123px">
							<div class="trigger_title">执行动作{{ indexOne + 1 }}</div>
							<el-row :gutter="20">
								<el-col :span="5" class="mb20">
									<el-form-item prop="triggerMode">
										<el-select disabled v-model="item.triggerMode" placeholder="请选择设备">
											<el-option :key="index" :label="item.label" :value="item.value" v-for="(item, index) in implementOptions"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 1">
									<el-form-item prop="equipmentName">
										<el-select disabled v-model="item.equipmentName" placeholder="请选择设备类型" @change="handleChangIptType($event, indexOne)">
											<el-option :key="index" :label="item.name" :value="item.identify" v-for="(item, index) in implementTypeOptions"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 1">
									<el-form-item prop="productName">
										<el-select disabled v-model="item.productName" placeholder="请选择设备产品" @change="handleChangIptProduct($event, indexOne)">
											<el-option
												:key="index1"
												:label="item1.name"
												:value="item1.productKey"
												v-for="(item1, index1) in item.productIptOptions"
											></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20 select_width" v-if="item.triggerMode == 1">
									<el-form-item prop="unitNo">
										<el-select disabled collapse-tags multiple filterable placeholder="请选择设备信息" v-model="item.unitNo" style="width: 300px">
											<template #header>
												<el-button text @click="changeUnitNo('action', true, indexOne)">全选</el-button>
												<el-button text @click="changeUnitNo('action', false, indexOne)">全取消</el-button>
											</template>
											<el-option
												:key="index2"
												:label="item2.deviceName"
												:value="item2.unitNo"
												v-for="(item2, index2) in item.accessDeviceInfoIptOptions"
												@click.native="handleChangIptInformation(item2, indexOne)"
											></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 1">
									<el-form-item prop="identifier">
										<el-select disabled v-model="item.identifier" placeholder="请选择设备下发" @change="handleChangDistribution($event, indexOne)">
											<el-option
												:key="index3"
												:label="item3.name"
												:value="item3.value"
												v-for="(item3, index3) in item.equipmentDistributionOptions"
											></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 1">
									<div disabled style="margin-left: 170px; cursor: pointer" @click="changeActionShow(item, indexOne)">高级<br />选项</div>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 1 && item.actionShow">
									<el-form-item prop="identifier">
										<el-input-number disabled placeholder="请输入延迟时间" v-model="item.delayTime" :min="0" :max="86400"> </el-input-number>
									</el-form-item>
								</el-col>
								<el-col :span="20"></el-col>
								<el-col
									v-for="param in item?.inputDataArr"
									:key="param.identifier"
									:span="10"
									class="mb20"
									style="padding-left: 125px"
									v-if="item.triggerMode == 1"
								>
									<el-form-item prop="params" :label="param.name + ':'">
										<el-input disabled v-if="param.dataType?.type === 'text'" v-model="param.value" auto-complete="off" />
										<el-input-number
											disabled
											v-if="param.dataType?.type === 'int32' || param.dataType?.type === 'float'"
											v-model="param.value"
											auto-complete="off"
										/>
										<el-radio-group disabled v-if="param.dataType?.type === 'bool'" v-model="param.value">
											<el-radio v-for="(value, key, index) in param.dataType?.specs" :key="index" :label="key">{{ value }}</el-radio>
										</el-radio-group>
										<el-select disabled v-if="param.dataType?.type === 'enum'" v-model="param.value" auto-complete="off">
											<el-option v-for="(value, key, index) in param.dataType?.specs" :key="index" :label="value" :value="key" />
										</el-select>
									</el-form-item>
								</el-col>
								<!-- 关联告警 -->
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 2">
									<el-form-item prop="alarmId">
										<el-select disabled v-model="item.alarmId" @change="alarmConfigChange($event, index)" placeholder="请选择告警配置">
											<el-option :key="index" :label="item.typeName" :value="item.typeCode" v-for="(item, index) in alarmConfigOptions"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 2">
									<el-form-item prop="alarmLevel">
										<el-select disabled v-model="item.alarmLevel" placeholder="请选择告警等级">
											<el-option :key="index" :label="item.label" :value="item.value" v-for="(item, index) in alarmLevelOptions"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 2">
									<el-form-item prop="alarmInfo">
										<el-select disabled v-model="item.alarmInfo" placeholder="请选择告警信息">
											<el-option :key="index" :label="item.label" :value="item.id" v-for="(item, index) in alarmInformationOptions"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<!-- 消息发送 -->
								<el-col :span="5" class="mb20" v-if="item.triggerMode == 3">
									<el-form-item prop="messageStatus">
										<el-select disabled v-model="item.messageStatus" placeholder="请选择消息发送类型">
											<el-option :key="index" :label="item.label" :value="item.value" v-for="(item, index) in messageSendingOptions"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
							</el-row>
						</div>
					</el-form>
				</div>
			</div>
		</el-form>
		<el-dialog v-model="centerDialogVisible" draggable title="特殊日期选择" width="600" align-center>
			<div>
				<div v-for="(it, indexTime) in form.sceneTriggerList" :key="indexTime">
					<div v-for="(it1, indexTime1) in it.timeList" :key="indexTime1">
						<div class="special_time">
							<el-date-picker disabled v-model="it1.specialDate" type="date" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
						</div>
					</div>
				</div>
			</div>
		</el-dialog>
	</el-dialog>
</template>

<script lang="ts" name="SysOauthClientDetailsDialog" setup>
import { useDict } from '/@/hooks/dict';
import { useMessage } from '/@/hooks/message';
// import { getObj, validateclientId } from '/@/api/admin/client';
import other from '/@/utils/other';
import {
	equipmentTypeList,
	accessProductList,
	accessDeviceInfoList,
	accessDevicePage,
	accessThingModelList,
	getlistServicesList,
	addObj,
	getDetails,
	putObj,
	getDetailUnit,
} from '/@/api/scene/sceneLinkage';
// import { BasicTableProps, useTable } from '/@/hooks/table';
import { useI18n } from 'vue-i18n';
import params from '/@/utils/params';
// import { rule } from '/@/utils/validate';
import { fetchList, fetchDictList } from '/@/api/alarm/alarmsetting';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const { t } = useI18n();
// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const service = ref([]);
// 定义字典
const { grant_types, common_status, captcha_flag_types, enc_flag_types } = useDict(
	'grant_types',
	'common_status',
	'captcha_flag_types',
	'enc_flag_types'
);
const conditionOptions = [
	{
		value: 0,
		label: '全部',
	},
	{
		value: 1,
		label: '任意一个',
	},
];
const changeIptShow = (val, indexOne) => {
	form.sceneTriggerList[indexOne].iptShow = !form.sceneTriggerList[indexOne].iptShow;
};
const changeActionShow = (val, index) => {
	form.sceneExecuteActionList[index].actionShow = !form.sceneExecuteActionList[index].actionShow;
};
const changeWeek = (val, value) => {
	if (val) {
		form.sceneTriggerList[value].week = ['1', '2', '3', '4', '5', '6', '7'];
	} else {
		form.sceneTriggerList[value].week = [];
	}
};

const intervalTimeMax = ref(86400);

const changeTiming = (val) => {
	let a = timeToSeconds(...val.split(':'));
	intervalTimeMax.value = 86400 - a;
};
const changeIntervalTimeMax = (val) => {
	if (val >= intervalTimeMax.value) {
		useMessage().warning('间隔时间不能超过今天!');
	}
};
function timeToSeconds(hours, minutes, seconds) {
	return Number(hours) * 3600 + Number(minutes) * 60 + Number(seconds);
}
// 提交表单数据
var form = reactive({
	id: '',
	sceneName: '',
	description: '',
	conditions: 0, // 执行条件
	type: '',
	actionType: '0',
	// 触发器
	sceneTriggerList: [] as any,
	// 执行条件
	sceneExecuteConditionsList: [] as any,
	// 执行动作
	sceneExecuteActionList: [
		{
			key: Date.now(),
			alarmId: '', //告警配置
			actionShow: false,
			delayTime: '', // 延迟时间
			triggerMode: 1, // 设备
			unitNo: '', // 设备编码  - 设备信息
			identifier: '',
			inputData: [],
			channelNo: '0', //
			channelValue: 0,
			alarmLevel: '', // 告警等级:1-一般、2-严重、3-紧急
			alarmInfo: '', // 告警信息
			messageStatus: '', // 消息发送（1.邮箱、2.钉钉、3.企业微信）
			params: [],
			inputDataArr: [],
			equipmentDistributionOptions: [],
			accessDeviceInfoIptOptions: [],
			productIptOptions: [],
		},
	] as any,
});

// 定义校验规则
const dataRules = ref({
	// sceneName: [{ required: true, message: '场景名称不能为空', trigger: 'blur' }],
	// type: [{ required: true, message: '请选择触发方式', trigger: 'change' }],
	// actionType: [{ required: true, message: '请选择业务类型', trigger: 'change' }],
});
const chufaqiRules = ref({
	// unitNo: [
	// 	{
	// 		type: 'array',
	// 		required: true,
	// 		message: '请选择设备信息',
	// 		trigger: 'change',
	// 	},
	// ],
});
const alarmConfigOptions = ref([]);
const alarmInformationOptions = ref([]);
const getAlarmConfigOptions = () => {
	fetchList().then((res) => {
		alarmConfigOptions.value = res.data.records.map((item) => {
			item.id = item.id + '';
			return { ...item };
		});
	});
	//
	fetchDictList({
		dictId: '1848249824998187010',
		dictType: 'alarm_info',
	}).then((res1) => {
		alarmInformationOptions.value = res1.data.records.map((item1) => {
			item1.id = item1.id + '';
			return { ...item1 };
		});
	});
};
const alarmConfigChange = (val, indx) => {
	let o = alarmConfigOptions.value.find((item) => item.typeCode === val);
	form.sceneExecuteActionList[indx].alarmLevel = o.level;
};

// 打开弹窗
const openDialog = (id: string) => {
	getAlarmConfigOptions();
	visible.value = true;
	form.id = '';
	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});
	if (id) {
		form.id = id;
		getsysOauthClientDetailsData(id);
	}
	equipmentList();
	implementList();
};
// 设备
const typeOptions = [
	{
		value: 1,
		label: '设备触发',
	},
	{
		value: 2,
		label: '定时触发',
	},
];
// 设备类型
var equipmentOptions = ref([]);
const equipmentList = () => {
	// 获取数据
	equipmentTypeList().then((res: any) => {
		// Object.assign(equipmentOptions, res.data);
		equipmentOptions.value = res.data;
	});
};

// 设备产品
// var productOptions = ref([]);
const handleChangType = (val, idx) => {
	if (typeof idx !== 'undefined') {
		// form.sceneTriggerList[idx].unitNo = [];
	}
	accessProductList({ category: val }).then((res: any) => {
		// Object.assign(productOptions, res.data);
		form.sceneTriggerList[idx].productOptions = res.data;
	});
};
// 设备信息
//var accessDeviceInfoOptions = ref([]);
const handleChangProduct = (val, idx) => {
	// accessDeviceInfoList({ productKey: val }).then((res: any) => {
	accessDevicePage({ current: 1, size: 999, productKey: val }).then((res: any) => {
		//Object.assign(accessDeviceInfoOptions, res.data.records);
		form.sceneTriggerList[idx].accessDeviceInfoOptions = res.data.records;
	});
};
// 信号类型
var informationOptions = ref([]);
const getCorpAndDept = (val, idx) => {
	accessThingModelList({ productKey: val }).then((res: any) => {
		//	Object.assign(informationOptions, res.data);
		form.sceneTriggerList[idx].informationOptions = res.data.model.properties;
	});
};

const changeUnitNo = (type, val, index) => {
	if (type === 'trigger') {
		form.sceneTriggerList[index].unitNo = val ? form.sceneTriggerList[index].accessDeviceInfoOptions.map((_) => _.unitNo) : [];
		getCorpAndDept(form.sceneTriggerList[index].accessDeviceInfoOptions[0].productKey, index);
	}
	if (type === 'conditions') {
		form.sceneExecuteConditionsList[index].unitNo = val ? form.sceneExecuteConditionsList[index].accessConditionOptions.map((_) => _.unitNo) : [];
		getConditionAndDept(form.sceneExecuteConditionsList[index].accessConditionOptions[0].productKey, index);
	}
	if (type === 'action') {
		form.sceneExecuteActionList[index].unitNo = val ? form.sceneExecuteActionList[index].accessDeviceInfoIptOptions.map((_) => _.unitNo) : [];
		handleChangIptInformation(form.sceneExecuteActionList[index].accessDeviceInfoIptOptions[0], index);
	}
};
const handleChangInformation = (val) => {
	// accessThingModelList().then((res: any) => {
	// 	Object.assign(informationOptions, res.data);
	// });
};
const timingOptions = [
	{
		value: 0,
		label: '设备',
	},
	{
		value: 1,
		label: '定时',
	},
];
// 触发类型
const triggerTypeOptions = [
	{
		value: 0,
		label: '>',
	},
	{
		value: 1,
		label: '<',
	},
	{
		value: 2,
		label: '=',
	},
	{
		value: 3,
		label: '范围值内',
	},
	{
		value: 4,
		label: '>=',
	},
	{
		value: 5,
		label: '<=',
	},
	{
		value: 6,
		label: '范围值外',
	},
];
// 触发机制
const mechanismOptions = [
	{
		value: 0,
		label: '立即触发',
	},
	{
		value: 1,
		label: '抑制重复',
	},
];
// 触发周期
const weekOptions = [
	{
		value: '7',
		label: '星期天',
	},
	{
		value: '1',
		label: '星期一',
	},
	{
		value: '2',
		label: '星期二',
	},
	{
		value: '3',
		label: '星期三',
	},
	{
		value: '4',
		label: '星期四',
	},
	{
		value: '5',
		label: '星期五',
	},
	{
		value: '6',
		label: '星期六',
	},
];
//
// 执行条件
const conditionForOptions = [
	{
		value: 1,
		label: '设备属性',
	},
	{
		value: 2,
		label: '时间范围',
	},
];
// 时间方式
const timeModeOptions = [
	{
		value: '1',
		label: '指定时间',
	},
	{
		value: '2',
		label: '一直生效',
	},
];
//  执行条件 设备产品
// const productConditionOptions = [];
const handleChangconditionType = (val, index) => {
	if (typeof index !== 'undefined') {
		// form.sceneExecuteConditionsList[index].unitNo = [];
	}
	accessProductList({ category: val }).then((res: any) => {
		// Object.assign(productConditionOptions, res.data);
		form.sceneExecuteConditionsList[index].productConditionOptions = res.data;
	});
};
// 设备信息
//const accessConditionOptions = [];
const handleChangConditionProduct = (val, index) => {
	// accessDeviceInfoList({ productKey: val }).then((res: any) => {
	accessDevicePage({ current: 1, size: 999, productKey: val }).then((res: any) => {
		// Object.assign(accessConditionOptions, res.data.records);
		form.sceneExecuteConditionsList[index].accessConditionOptions = res.data.records;
	});
};

//var informationConditionOptions = ref([]);
const getConditionAndDept = (val, index) => {
	accessThingModelList({ productKey: val }).then((res: any) => {
		//	Object.assign(informationOptions, res.data);
		form.sceneExecuteConditionsList[index].informationConditionOptions = res.data.model.properties;
	});
};

// 信号类型
const handleChangConditionInformation = (val) => {
	// accessThingModelList().then((res: any) => {
	// 	Object.assign(informationConditionOptions, res.data);
	// });
};
var onlineOffline = ref('');
const handleOnlineOffline = (val) => {
	onlineOffline.value = val;
};
var onlineOfflineOne = ref('');
const handleOnlineOfflineOne = (val) => {
	onlineOfflineOne.value = val;
};
// 执行动作
// 告警等级
const alarmLevelOptions = [
	{
		value: '1',
		label: '一般',
	},
	{
		value: '2',
		label: '严重',
	},
	{
		value: '3',
		label: '紧急',
	},
];
// 消息发送
const messageSendingOptions = [
	{
		value: 1,
		label: '邮箱',
	},
	{
		value: 2,
		label: '钉钉',
	},
	{
		value: 3,
		label: '企业微信',
	},
];
// 设备执行
const implementOptions = [
	{
		value: 1,
		label: '设备输出',
	},
	{
		value: 2,
		label: '关联告警',
	},
	// {
	// 	value: 3,
	// 	label: '消息发送',
	// },
];
// 执行 设备类型
const implementTypeOptions = [];
const implementList = () => {
	// 获取数据
	equipmentTypeList().then((res: any) => {
		Object.assign(implementTypeOptions, res.data);
	});
};
// 执行 设备产品
//var productIptOptions = ref([]);
const handleChangIptType = (val, idx) => {
	if (typeof idx !== 'undefined') {
		// form.sceneExecuteActionList[idx].unitNo = [];
	}
	accessProductList({ category: val }).then((res: any) => {
		// Object.assign(productIptOptions, res.data);
		form.sceneExecuteActionList[idx].productIptOptions = res.data;
	});
};
// 执行 设备信息
//var accessDeviceInfoIptOptions = ref([]);
const handleChangIptProduct = (val, idx) => {
	// accessDeviceInfoList({ productKey: val }).then((res: any) => {
	accessDevicePage({ current: 1, size: 999, productKey: val }).then((res: any) => {
		// Object.assign(accessDeviceInfoIptOptions, res.data.records);
		form.sceneExecuteActionList[idx].accessDeviceInfoIptOptions = res.data.records;
	});
};
// 设备下发
//const equipmentDistributionOptions = ref([]);
// const servicesDataList = [];
const handleChangIptInformation = (val, idx) => {
	console.log(val);
	// form.sceneExecuteActionList.identifier = '';
	getlistServicesList({ productKey: val.productKey == null ? val.productName : val.productKey }).then((res: any) => {
		form.sceneExecuteActionList[idx].equipmentDistributionOptions = res.data;
	});
	getDetailUnit({ unitNo: Array.isArray(val.unitNo) ? val.unitNo[0] : val.unitNo }).then((res: any) => {
		service.value = res.data.services || [];
		let arr = service.value.filter((a) => a.identifier == val.identifier);
		let inputDataArr = arr[0]?.inputData;
		// 设备 下发指令参数值回显

		val.sceneExecuteActionModelList.forEach((obj) => {
			inputDataArr.forEach((item) => {
				if (obj.circuitId == item.identifier) {
					item.value = obj?.value;
					item.name = obj.name;
					obj.name = obj.name;
					obj.value = obj.value;
					obj.dataType = item.dataType;
				}
			});
		});
		form.sceneExecuteActionList[idx].inputDataArr = inputDataArr;
	});
};
const handleChangDistribution = (val, index) => {
	let arr = service.value.filter((item) => item.identifier == val);
	form.sceneExecuteActionList[index].inputDataArr = arr[0]?.inputData;
};
const formatDateTime = (isoString) => {
	const date = new Date(isoString);
	const hours = date.getHours().toString().padStart(2, '0');
	const minutes = date.getMinutes().toString().padStart(2, '0');
	const seconds = date.getSeconds().toString().padStart(2, '0');
	return `${hours}:${minutes}:${seconds}`;
};
const getYMDHMS = (timestamp) => {
	let time = new Date(timestamp);
	let year = time.getFullYear();
	let month = time.getMonth() + 1;
	let date = time.getDate();
	let hours = time.getHours();
	let minute = time.getMinutes();
	let second = time.getSeconds();
	if (month < 10) {
		month = '0' + month;
	}
	if (date < 10) {
		date = '0' + date;
	}
	if (hours < 10) {
		hours = '0' + hours;
	}
	if (minute < 10) {
		minute = '0' + minute;
	}
	if (second < 10) {
		second = '0' + second;
	}
	return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second;
};
const route = useRoute();
const router = useRouter();
onMounted(() => {});
const formItem = ref(null);
// 新增 / 编辑  取消按钮清空事件
const onCancel = () => {
	nextTick(() => {
		dataFormRef.value?.resetFields();
		form.sceneTriggerList = [];
		form.sceneExecuteConditionsList = [];
		form.sceneExecuteActionList = [
			{
				id: '',
				key: Date.now(),
				triggerMode: 1, // 设备
				unitNo: '', // 设备编码  - 设备信息
				channelNo: '0',
				identifier: '',
				actionShow: false,
				delayTime: '',
				channelValue: 0,
				inputDataArr: [],
				alarmId: '',
				alarmLevel: '', // 告警等级:1-一般、2-严重、3-紧急
				alarmInfo: '',
				messageStatus: '', // 消息发送（1.邮箱、2.钉钉、3.企业微信）
				equipmentDistributionOptions: [],
				accessDeviceInfoIptOptions: [],
				productIptOptions: [],
			},
		];
	});
	visible.value = false;
};
// 初始化表单数据 - 详情
const getsysOauthClientDetailsData = (id: string) => {
	loading.value = true;
	// 获取数据
	const key = 'specialDate';
	getDetails(id).then((res: any) => {
		//Object.assign(form, res.data);
		form.linkageId = res.data.linkageId;
		form.sceneName = res.data.sceneName; // 场景名称
		form.type = res.data.type;
		form.actionType = res.data.actionType;
		form.description = res.data.description; // 场景描述
		form.sceneTriggerList = []; // 触发器
		form.sceneExecuteConditionsList = []; // 场景执行条件
		form.sceneExecuteActionList = []; // 场景执行动作
		// 触发器
		res.data.sceneTriggerList.map((item, index) => {
			setTimeout(() => {
				if (item.triggerMode == 1) {
					var one = {};
					one.triggerMode = item.triggerMode; // 设备
					one.equipmentName = item.name; // 设备类型
					one.identify = item.identify; // 设备类型编码
					one.productName = item.productName; // 设备产品
					one.productKey = item.productKey; // 设备产品编码
					one.deviceName = item.deviceName; // 设备信息
					one.unitNo = item.unitNo?.split(','); // 设备信息编码
					one.channelNo = item.channelNo; // 设备 信号类型
					one.unit = item.unit; // 设备 信号类型单位
					one.configType = item.configType; // 设备  触发类型
					one.fixedValue = item.fixedValue; // 设备  固定值
					one.upperValue = item.upperValue; // 设备  上限值
					one.lowerValue = item.lowerValue; // 设备  下限值
					one.triggerConfig = item.triggerConfig; // 设备  触发机制
					one.second = item.setTime; // 设备  触发秒数
					one.productOptions = []; //设备产品下拉数据
					one.accessDeviceInfoOptions = []; //设备信息下拉数据
					one.informationOptions = []; //信号类型下拉数据
					handleChangType(item.name, index); // 设备产品
					handleChangProduct(item.productName, index); // 设备信息
					getCorpAndDept(item.productName, index); // 信息类型
					form.sceneTriggerList.push(one);
				} else if (item.triggerMode == 2) {
					var two = {};
					two.triggerMode = item.triggerMode; // 设备
					two.timingSetTime = item.setTime; //开始时间
					// two.week = item.week.split(','); // 定时 周期
					// two.week = item.week == null ? '' : item.week.split(','); // 定时 周期
					two.week = item.week == null ? '' : item.week === '' ? '' : item.week.split(','); // 定时 周期
					two.triggerNumber = item.triggerNumber; // 定时 重复触发次数
					two.intervalTime = item.intervalTime; // 定时 间隔时间
					if (item.triggerNumber || item.intervalTime) {
						two.iptShow = true;
					}
					two.timeList = item.specialDateList; // 定时 特殊日期
					form.sceneTriggerList.push(two);
				}
			}, 900);
		});
		form.conditions = res.data.sceneExecuteConditionsList[0]?.conditions;
		// 执行条件
		res.data.sceneExecuteConditionsList.map((item, index) => {
			setTimeout(() => {
				if (item.triggerMode == 1) {
					var tiaojian1 = {};
					// 设备
					tiaojian1.triggerMode = item.triggerMode; // 设备
					tiaojian1.equipmentName = item.name; // 设备类型
					tiaojian1.identify = item.identify; // 设备类型编码
					tiaojian1.productName = item.productName; // 设备产品
					tiaojian1.productKey = item.productKey; // 设备产品编码
					tiaojian1.deviceName = item.deviceName; // 设备信息
					tiaojian1.unitNo = item.unitNo?.split(','); // 设备信息编码
					tiaojian1.channelNo = item.channelNo; // 设备 信号类型
					tiaojian1.unit = item.unit; // 设备 信号类型单位
					tiaojian1.configType = item.configType; // 设备  触发类型
					tiaojian1.fixedValue = item.fixedValue; // 设备  固定值
					tiaojian1.upperValue = item.upperValue; // 设备  上限值
					tiaojian1.lowerValue = item.lowerValue; // 设备  下限值
					tiaojian1.productConditionOptions = []; //执行条件设备产品下拉数据
					tiaojian1.accessConditionOptions = []; //执行条件设备信息下拉数据
					tiaojian1.informationConditionOptions = []; //执行条件信号类型下拉数据
					handleChangconditionType(item.name, index); // 设备产品
					handleChangConditionProduct(item.productName, index); // 设备信息
					getConditionAndDept(item.productName, index); // 信息类型
					form.sceneExecuteConditionsList.push(tiaojian1);
				} else if (item.triggerMode == 2) {
					var tiaojian2 = {};
					// 时间范围
					tiaojian2.conditions = item.conditions; // 任意一个
					tiaojian2.triggerMode = item.triggerMode; // 触发器模式
					tiaojian2.timeScope = item.timeScope; //
					tiaojian2.startTime = getYMDHMS(item.startTime); // 开始时间
					tiaojian2.endTime = getYMDHMS(item.endTime); //  结束时间
					form.sceneExecuteConditionsList.push(tiaojian2);
				}
			}, 1300);
		});
		// 执行动作
		res.data.sceneExecuteActionList.map((item, index) => {
			setTimeout(() => {
				if (item.triggerMode == 1) {
					item.equipmentName = item.name;
					item.unitNo = item.unitNo?.split(',');
					if (item.delayTime !== null) {
						item.actionShow = true;
					}
					item.inputDataArr = item.sceneExecuteActionModelList;
					item.equipmentDistributionOptions = [];
					item.accessDeviceInfoIptOptions = [];
					item.productIptOptions = [];
					handleChangIptType(item.name, index); // 设备产品
					handleChangIptProduct(item.productName, index); // 设备信息
					handleChangIptInformation(item, index); // 信息类型
					form.sceneExecuteActionList.push(item);
				} else if (item.triggerMode == 2) {
					var dongzuo2 = {};
					// 时间范围
					dongzuo2.triggerMode = item.triggerMode; // 触发器模式
					dongzuo2.alarmLevel = item.alarmLevel + ''; // 告警等级:1-一般、2-严重、3-紧急
					dongzuo2.alarmInfo = item.alarmInfo + ''; //
					dongzuo2.alarmId = item.alarmId; //
					Object.assign(form.sceneExecuteActionList.push(dongzuo2));
				} else if (item.triggerMode == 3) {
					var dongzuo3 = {};
					// 时间范围
					dongzuo3.triggerMode = item.triggerMode; // 触发器模式
					dongzuo3.messageStatus = item.messageStatus; // 消息发送（1.邮箱、2.钉钉、3.企业微信）
					Object.assign(form.sceneExecuteActionList.push(dongzuo3));
				}
			}, 1000);
		});
		setTimeout(() => {
			loading.value = false;
		}, 2000);
	});
};

const centerDialogVisible = ref(false);
const handleSpecialDates = (val, i) => {
	centerDialogVisible.value = true;
};
const handleChangeMiaoshi = (value) => {
	console.log(value);
};
const handleChangeKaiguan = (value) => {
	console.log(value);
};
// 暴露变量
defineExpose({
	openDialog,
});
</script>
<style lang="scss" scoped>
.box {
	display: flex;
	// align-items: center;
	.chufaqi {
		width: 93%;
		background-color: #f0f0f0;
		padding: 4px;
		margin-bottom: 5px;
		border-radius: 4px;
	}
}
.trigger_title {
	padding: 5px 10px;
	color: #000;
}
.box_del {
	cursor: pointer;
	margin-left: -70px;
	// color: #fff;
	width: 80px;
}
.box_add {
	cursor: pointer;
	margin: 2px 0 2px 0;
	// color: #32cd99;
	display: inline-block;
}
.shaixuan_select {
	display: flex;
	align-items: center;
	margin-bottom: 5px;
	.manzu {
		margin: 0 10px 0 15px;
	}
	.tiaojian {
		margin-left: 10px;
	}
}
::v-deep .el-select__wrapper {
	// background-color: red;
	//background-color: var(--el-fill-color-blank);
}
.special_time {
	margin-top: 10px;
	display: flex;
	align-items: center;
	.special_del {
		margin-left: 10px;
		cursor: pointer;
	}
}
.title_name {
	display: flex;
	justify-content: space-between;
	width: 92%;
}
.mb20 {
	margin-bottom: -2px !important;
}
::v-deep .el-row {
	margin-left: -120px !important;
	margin-right: 100px !important;
}
::v-deep .el-form-item__label {
	// color: #fff !important;
}
::v-deep .el-form-item {
	width: 320px;
}
.select_width {
	::v-deep .el-select__tags-text {
		width: 40px;
	}
}
</style>
